<?php

namespace app\models;

use yii\base\Model;

/**
 * 子用户用户登录表单
 * Class SubUserLoginForm
 * @package app\models
 */
class SubUserLoginForm extends Model
{
    /**
     * @var integer 所属用户编号
     */
    public $uid;
    /**
     * @var string 用户名
     */
    public $username;
    /**
     * @var string 登录密码
     */
    public $password;
    /**
     * @var bool 是否记住登录状态
     */
    public $rememberMe = false;
    /**
     * @var bool|SubUser 登录用户信息
     */
    private $_user = false;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['uid', 'username', 'password'], 'required'],
            ['rememberMe', 'boolean'],
            ['password', 'validatePassword'],
        ];
    }

    /**
     * 验证登录密码
     */
    public function validatePassword()
    {
        if (!$this->hasErrors()) {
            if ($this->_user === false) {
                $this->_user = SubUser::find()
                    ->where(['uid' => $this->uid, 'username' => $this->username, 'status' => [SubUser::STATUS_OK, SubUser::STATUS_STOP]])
                    ->one();
                if (!empty($this->_user) && $this->_user->status == SubUser::STATUS_STOP) {
                    $this->addError('username', '此账号已停用。');
                }
            }
            if (!$this->_user || !$this->_user->validatePassword($this->password)) {
                $this->addError('password', '用户名或密码错误。');
            }
        }
    }

    /**
     * 登录操作
     * @return bool
     */
    public function login()
    {
        if ($this->validate()) {
            $this->_user->updateAttributes(['auth_key' => Util::randomStr(32, 7)]);
            return true;
        }
        return false;
    }

    /**
     * 获取登录用户
     * @return SubUser
     */
    public function getUser()
    {
        return $this->_user;
    }
}
